package com.example.musicplayer;


import android.Manifest;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;

import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.musicplayer.activity.MusicPlayerActivity;
import com.example.musicplayer.adapter.MusicAdapter;
import com.example.musicplayer.base.BaseActivity;
import com.example.musicplayer.pojo.Music;
import com.example.musicplayer.service.MusicService;
import com.example.musicplayer.utils.LogUtil;
import com.example.musicplayer.utils.MusicUtils;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    private RecyclerView recyclerView;
    private List<Music> musicList;  // 音乐文件集合
    private MusicAdapter adapter;
    private Context mContext;
    private ImageView ivStartAndPause; // 主界面开始和暂停按钮
    private TextView ivMainMusicNameAndAuthor; // 主界面正在播放的音乐

    private MusicService musicService = new MusicService();
    private Integer isPlayingPosition; // 记录正在播放的歌曲
    private boolean isStartUp = true; // 判断是否是第一次进入应用程序
    private LinearLayout ll_into_play; // 点击主界面进入播放页面

    private static final String UPDATE_ACTION = "com.example.action.UPDATE_ACTION";

    private MusicService.MusicPlayBinder musicPlayBinder;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicPlayBinder = (MusicService.MusicPlayBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recycler_view);
        ivMainMusicNameAndAuthor = findViewById(R.id.iv_main_music_name_and_author);
        ivStartAndPause = findViewById(R.id.iv_start_and_pause);
        ll_into_play = findViewById(R.id.ll_into_play);

        ll_into_play.setOnClickListener(this);
        ivStartAndPause.setOnClickListener(this);

        Intent intent = new Intent(this, MusicService.class);
        startService(intent); // 启动服务
        bindService(intent, connection, BIND_AUTO_CREATE); // 绑定服务

        // 对读取系统资源进行授权(运行时权限)
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            // 将Musics信息显示在界面上
            appendMusicToView();
        }
    }

    /**
     * 将Musics信息显示在界面上
     */
    private void appendMusicToView() {
        musicList = MusicUtils.getMusicList(mContext);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MusicAdapter(mContext, musicList);
        recyclerView.setAdapter(adapter);
        ivMainMusicNameAndAuthor.setText("您还没有播放音乐");

        //点击RecyclerView Item 的点击事件
        ClickAdapterListener();
    }

    /**
     * 绑定RecyclerView Item 的点击事件
     */
    private void ClickAdapterListener() {
        adapter.setOnItemClickListener(new MusicAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                isStartUp = false;
                // 获取当前点击的音乐
                Music music = musicList.get(position);
                // 记录当前正在播放的音乐
                isPlayingPosition = position;
                // 播放音乐
                musicPlayBinder.startMusic(music.getMusicPath());
                // 设置歌曲名
                ivMainMusicNameAndAuthor.setText(music.getMusicName());
                // 设置为开始图标
                ivStartAndPause.setImageResource(R.mipmap.start);
            }
        });
    }
    /**
     * 用户同意或拒绝之后，回调到此方法，授权的结果封装在grantResults参数中
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    appendMusicToView();
                } else {
                    Toast.makeText(this, "拒绝权限无法使用程序", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }
    /**
     * 点击事件
     * @param v
     */
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            // 首页开始和暂停
            case R.id.iv_start_and_pause:
                Log.e("点击了", "哈哈哈哈");
                if (musicService.getMediaPlayer().isPlaying()) {
                    musicService.getMediaPlayer().pause();
                    ivStartAndPause.setImageResource(R.mipmap.pause);
                    isStartUp = false;
                } else {
                    // 如果是第一次启动就播放第一首音乐
                    if(isStartUp) {
                        Music music = musicList.get(0);
                        try {
                            musicService.getMediaPlayer().setDataSource(music.getMusicPath());
                            musicService.getMediaPlayer().prepare();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        musicService.getMediaPlayer().start();
                    }
                    musicService.getMediaPlayer().start();
                    ivStartAndPause.setImageResource(R.mipmap.start);
                }
                break;
            case R.id.ll_into_play:
                Intent intentPlay = new Intent(MainActivity.this, MusicPlayerActivity.class);
                intentPlay.putExtra("musicList", (Serializable) musicList);
                // 如果没有音乐播放
                if (!musicService.getMediaPlayer().isPlaying()) {
                    startActivity(intentPlay);
                } else {
                    // 如果音乐正在播放,将当前音乐传入第二个Activity
                    intentPlay.putExtra("MusicPosition", isPlayingPosition);
                    startActivity(intentPlay);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 活动处于暂停状态
     */
    @Override
    protected void onPause() {
        super.onPause();
        LogUtil.d("你销毁了吗", "销毁了");
    }

}